package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    // 查询所有学生信息
    @Autowired
    private ClazzService clazzService;
    @Override
    public PageResult getStuAndClazzName(StudentQueryParam sqp) {
        //1. 查询所有学生信息
        Page<Student> page = new Page<>(sqp.getPage(), sqp.getPageSize());
        Page<Student> studentPage = page(page, new LambdaQueryWrapper<Student>()
                .like(sqp.getName()!= null && !sqp.getName().isEmpty(),  Student::getName, sqp.getName())
                .eq(sqp.getDegree() != null, Student::getDegree, sqp.getDegree())
                .eq(sqp.getClazzId() != null, Student::getClazzId, sqp.getClazzId()));
        // 2. 查询所有班级信息
        List<Student> studentList = studentPage.getRecords();
        List<Clazz> clazzList = clazzService.list();
        for (Clazz clazz : clazzList) {
            studentList.forEach(student -> {
                if (student.getClazzId().equals(clazz.getId())) {
                    student.setClazzName(clazz.getName());
                }
            });
        }
        PageResult pageResult = new PageResult(studentPage.getTotal(), studentPage.getRecords());
        return pageResult;
    }
    // 更新学生违纪
    @Override
    public void updateScoreById(Integer id, Integer score) {
        Student student = getById(id);
        student.setViolationScore((short) (student.getViolationScore() + score));
        student.setViolationCount((short) (student.getViolationCount() + 1));
        student.setUpdateTime(LocalDateTime.now());
        updateById(student);
    }
}
